import { Effect, Reducer } from 'umi';
import {
  getArticleList,
  getArticleRecommend,
  getArchiveList,
  getTagList,
} from '@/services';
import { IArchiveItem, IArticleItem, TagItem } from '@/types';

export interface ArticleModelState {
  articleList: IArticleItem[];
  recommedArticleList: IArticleItem[];
  articleLength: number;
  archiveList: IArchiveItem[];
  archiveLength: number;
  tagList: TagItem[];
}

export interface ArticleModelType {
  namespace: 'article';
  state: ArticleModelState;
  effects: {
    getArticleList: Effect;
    getArticleRecommend: Effect;
    getArchiveList: Effect;
    getTagList: Effect;
  };
  reducers: {
    save: Reducer<ArticleModelState>;
  };
}

const ArticleModel: ArticleModelType = {
  namespace: 'article',
  state: {
    articleList: [],
    recommedArticleList: [],
    articleLength: 0,
    archiveList: [],
    archiveLength: 0,
    tagList: [],
  },

  effects: {
    // 获取文章列表
    *getArticleList({ payload }, { call, put }) {
      const result = yield call(getArticleList);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            articleList: result.data[0],
            articleLength: result.data[1],
          },
        });
      }
    },
    *getArticleRecommend({ payload }, { call, put }) {
      const result = yield call(getArticleRecommend);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            recommedArticleList: result.data,
          },
        });
      }
    },
    // 获取归档列表
    *getArchiveList({ payload }, { call, put }) {
      const result = yield call(getArchiveList);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            archiveList: result.data[2022].January,
            archiveLength: result.data[2022].January.length,
          },
        });
      }
    },
    // 获取标签列表
    *getTagList({ payload }, { call, put }) {
      const result = yield call(getTagList);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            tagList: result.data,
          },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default ArticleModel;
